using System.Globalization;

namespace RadioTimer.Converters
{
    /// <summary>
    /// 颜色到渐变画笔转换器
    /// 将单一颜色转换为渐变效果画笔，用于按钮背景
    /// </summary>
    public class ColorToGradientBrushConverter : IValueConverter
    {
        /// <summary>
        /// 将颜色值转换为渐变画笔
        /// </summary>
        /// <param name="value">输入的颜色值</param>
        /// <param name="targetType">目标类型</param>
        /// <param name="parameter">转换参数</param>
        /// <param name="culture">文化信息</param>
        /// <returns>线性渐变画笔</returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Color color)
            {
                // 创建线性渐变画笔，从亮色到暗色的渐变效果
                var gradientBrush = new LinearGradientBrush
                {
                    StartPoint = new Point(0, 0),
                    EndPoint = new Point(1, 1)
                };

                // 计算渐变色：主色和加深色
                var lighterColor = LightenColor(color, 0.2f);
                var darkerColor = DarkenColor(color, 0.2f);

                // 添加渐变停止点
                gradientBrush.GradientStops.Add(new GradientStop(lighterColor, (float)0.0));
                gradientBrush.GradientStops.Add(new GradientStop(color, (float)0.5));
                gradientBrush.GradientStops.Add(new GradientStop(darkerColor, (float)1.0));

                return gradientBrush;
            }

            // 如果无法转换，返回默认的透明画笔
            return new SolidColorBrush(Colors.Transparent);
        }

        /// <summary>
        /// 反向转换（不支持）
        /// </summary>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 亮化颜色
        /// </summary>
        /// <param name="color">原始颜色</param>
        /// <param name="factor">亮化因子</param>
        /// <returns>亮化后的颜色</returns>
        private Color LightenColor(Color color, float factor)
        {
            var r = (int)Math.Min(255, color.Red * 255 + (255 - color.Red * 255) * factor);
            var g = (int)Math.Min(255, color.Green * 255 + (255 - color.Green * 255) * factor);
            var b = (int)Math.Min(255, color.Blue * 255 + (255 - color.Blue * 255) * factor);
            return Color.FromRgb((byte)r, (byte)g, (byte)b);
        }

        /// <summary>
        /// 暗化颜色
        /// </summary>
        /// <param name="color">原始颜色</param>
        /// <param name="factor">暗化因子</param>
        /// <returns>暗化后的颜色</returns>
        private Color DarkenColor(Color color, float factor)
        {
            var r = (int)Math.Max(0, color.Red * 255 * (1 - factor));
            var g = (int)Math.Max(0, color.Green * 255 * (1 - factor));
            var b = (int)Math.Max(0, color.Blue * 255 * (1 - factor));
            return Color.FromRgb((byte)r, (byte)g, (byte)b);
        }
    }
}